<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                <template slot="menuLeft">
                    <div>
                        <el-button type="primary" size="small" @click="dialogFormVisible = true">新增</el-button>
                        <el-dialog title="新增市场行情" :visible.sync="dialogFormVisible">
                            <el-form :model="form">
                                <el-form-item label="商品名称:" prop="goodsName" label-width="15%">
                                  <el-select
                                    clearable
                                    filterable
                                    default-first-option
                                    v-model="selectGoods.goodsName"
                                    remote :remote-method="searchGoodsByName(selectGoods)"
                                    :loading="selectGoods.loading"
                                    @change="onGoodsSelectChange($event, selectGoods)"
                                    placeholder="请输入商品名称"
                                    style="width: 40% !important">
                                    <el-option
                                      v-for="item in selectGoods.goodsList"
                                      :key="item.id" :label="item.goodsName"
                                      :value="item.id">
                                    </el-option>
                                  </el-select>
                                  <!--<el-button type="text" @click="showGoodsDialog()" style="width: 10%">所有商品</el-button>-->
                                </el-form-item>
                              <el-form-item label="商品图片" label-width="15%" required>
                                <el-image
                                  style="display: inline-block ; width: 100px; height: 100px;background-color: yellow"
                                  :src="form.goodsImg"
                                  fit="fill"></el-image>
                              </el-form-item>
                              <el-form-item label="规格:" prop="goodsId" label-width="15%">
                                  <el-select class="form-field"
                                             v-model="selectGoods.goodsId"
                                             @change="onModelSelectChange($event, selectGoods)"
                                             placeholder="请选择"
                                             style="width: 40% !important">
                                    <el-option
                                      v-for="item in selectGoods.goodsModelList"
                                      :key="item.id"
                                      :label="item.modelName+' /单位:'+item.modelUnit"
                                      :value="item.id">
                                    </el-option>
                                  </el-select>
                                </el-form-item>

                                <el-form-item label="市场价" label-width="15%" required>
                                    <el-input v-model="form.marketPrice" type="number" oninput="if(value.length>8)value=value.slice(0,8)" autocomplete="off" style="width: 40%"></el-input>
                                </el-form-item>
                                <el-form-item label="记录时间" label-width="15%" required>
                                    <div style="width: 40%;display: inline-block">
                                        <el-date-picker
                                                value-format="yyyy-MM-dd HH:mm:ss"
                                                v-model="form.recordTime"
                                                type="date"
                                                placeholder="选择日期">
                                        </el-date-picker>
                                    </div>
                                </el-form-item>
                                <el-form-item label="选择供应商" label-width="15%" required >
                                  <el-select v-model="form.supplierName" placeholder="选择供应商" style="width: 40% !important" @change="getSup">
                                    <el-option v-for="item in supList" :label="item.supplierName" :value="item.id" :key="index"></el-option>
                                  </el-select>
                                </el-form-item>
                                <el-form-item label="采购员" label-width="15%" required>
                                  <el-select v-model="form.initiatorId" placeholder="选择采购员" style="width: 40% !important">
                                    <el-option v-for="item in gridData" :label="item.name" :value="item.id" :key="index"></el-option>
                                  </el-select>
                                </el-form-item>
                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="confirm">保存</el-button>
                            </div>
                        </el-dialog>
                    </div>
                </template>
            </avue-crud>
        </basic-container>
    </div>
</template>

<script>
    import {
        fetchList,
        getObj,
        addObj,
        putObj,
        delObj,
        addQuotation
    } from '@/api/scm/purchase/market_quotation'
    import {
        tableOption
    } from '@/const/crud/scm/purchase/market_quotation'
    //采购员
    import {
      queryEmployeeList,
    } from '@/api/scm/purchase/purchase_task'
    //供应商
    import {
      fetchList as fetchcList,
    } from '@/api/supply/supplier'
    import {
        mapGetters
    } from 'vuex'
    import Request from '../../order/request.js'
    import Util from '@/util/pds/utils';
    let cookieUtil = new Util();
    import {getStore, setStore} from "@/util/store";
    export default {
        name: 'suppliergrade',
        data() {
            return {
                request: new Request(),
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption,
                form:{
                    goodsName:'',
                    goodsModelId:'',
                    modelName:'',
                    marketPrice:0,
                    recordTime:'',
                    supplierName:'',
                    supplierId:'',
                    initiatorId:'',
                    goodsImg:'',
                    unit:'',
                    goodsCategoryId:''
                },
                selectGoods: {
                  goodsName: '',
                  loading: '',
                  goodsList: [],
                  goodsId: '',
                  goodsModelList: []
                },
                dialogFormVisible: false,
                gridData:[],//采购员
                supList:[],
                pmId: ''
            }
        },
        created() {
            this.pmId = this.getStore({name: "pmId"});
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.purchase_purchasetask_add, true),
                    delBtn: this.vaildData(this.permissions.purchase_purchasetask_del, true),
                    editBtn: this.vaildData(this.permissions.purchase_purchasetask_edit, true)
                };
            }
        },
        methods: {
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params)).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                })
                this.getGird();
                this.getsupList();
            },
            rowDel: function (row, index) {
                var _this = this
                this.$confirm('是否确认删除ID为' + row.id, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.tableData.splice(index, 1)
                    _this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getList(this.page)
                }).catch(function (err) {
                })
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (row, index, done) {
                putObj(row).then(data => {
                    this.tableData.splice(index, 1, Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (row, done) {
                addObj(row).then(data => {
                    this.tableData.push(Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },
            getGird(){
              //查询采购员
              queryEmployeeList({
                pmId: this.pmId,
                purchaseEmployeeType: "3"
              }).then(res => {
                this.gridData = res.data.data
              })
            },
           //获取供应商
            getsupList(params) {
              this.tableLoading = true
              fetchcList(Object.assign({
                current: 1,
                size: 20
              }, params)).then(response => {
                this.supList = response.data.data.records
              })
            },
            getSup(val){
              console.log(this.form);
              this.form.supplierId = val;
              this.supList.forEach(item=>{
                if(item.id == val){
                  this.form.supplierName = item.supplierName;
                }
              })
            },
            // 搜索商品
            searchGoodsByName(row) {
              // 将row信息传入
              let _this = this;
              return function (searchValue) {
                if (searchValue !== '') {
                  row.loading = true
                  console.log('time', searchValue);
                  let params = {
                    goodsName: searchValue,
                  }
                  params.buyerId = _this.buyerId;
                  params.shopId = getStore({name: "shopId"})
                  params.pageNo = _this.currentPage
                  params.pageSize = _this.pageSize
                  params.goodsName = searchValue
                  _this.request.getGoodsList(params).then(res => {
                    if (res.code == 200) {
                      _this.$set(row, 'goodsList', res.ext.list);
                      _this.$set(row, 'loading', false);
                      _this.goodsList = res.ext.list
                      _this.currentPage = res.ext.pageNo
                      _this.totalCount = res.ext.count
                    } else if (res.code == '983') {
                      _this.goodsList = []
                    } else {
                      _this.$message.error('请求失败')
                    }
                  })
                }
              }
            },
            //选择商品
            onGoodsSelectChange(e, row) {
              if(e){
                let selectedGoods = row.goodsList.filter(item => item.id === e)[0]
                row.goodsModelList = selectedGoods.goodsModelList
                this.$set(row, 'goodsName', selectedGoods.goodsName)
                this.$set(row, 'thumbUrl', selectedGoods.thumbUrl)
                this.onModelSelectChange(selectedGoods.goodsModelList[0].id, row)
                this.form.goodsImg = selectedGoods.thumbUrl;
                this.form.goodsName = selectedGoods.goodsName;
                console.log(selectedGoods);
                this.form.goodsCategoryId = selectedGoods.categoryId;
                row.goodsModel = ''
              }else{
                // 清空选项时
                this.$set(row, 'goodsId', '');
                row.goodsId = '';
              }
            },
            //选择规格
            onModelSelectChange(e, row) {
              let selectedModel = row.goodsModelList.filter(item => item.id === e)[0]
              this.form.goodsModelId = selectedModel.id;
              this.form.modelName=selectedModel.modelName;
              this.form.unit=selectedModel.modelUnit;
            },
            showGoodsDialog() {
              this.dialogVisible = true
            },
            //新增市场行情
            confirm(){
              let param = this.form;
              param.pmId= this.pmId;
              console.log("param",param);
              addQuotation(param).then(res =>{
                console.log(res);
                if(res.data.code == 0){
                  this.$message.success("新增成功");
                  this.getList(this.page);
                  this.dialogFormVisible = false;
                }else{
                  this.$message.error("新增失败")
                }
              });
            },
            /**
             * 搜索回调
             */
            searchChange(form, done) {
                this.getList(this.page, form);
                done();
            },
            /**
             * 刷新回调
             */
            refreshChange(info) {
    this.getList(this.page, this.filterForm(info.searchForm));
}
        }
    }
</script>

<style lang="scss" scoped>
</style>
